<?php
/**支付控制器*/
namespace App\Http\Controllers;
use App\Http\Models\Address;
use App\Http\Models\Bill;
use App\Http\Models\Log;
use App\Http\Models\Order;
use App\Http\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use phpDocumentor\Reflection\Types\Null_;
class PayController extends Controller
{
    //
    public function __construct()
    {
        $this->nav = '家具租赁';
        $this->bill = new Bill();
    }

    /**订单支付*/
    public function paybill()
    {
        $this->user =User::find(session('user')->id);
        $param['cart'] = CommonController::shopcart(session('user')->id);
        $id = Input::get('id');
        $param['paybill'] = Order::where('id',$id)
        ->where('orders_user_id',session('user')->id)
        ->where('orders_status',0)
        ->first();
        if($param['paybill'] == ''){
            return view('errors.404');
        }
            if($param['paybill']->orders_discount > 0) {
                //查看优惠券是否过期
                $cop_id = DB::table('coupon_detail')->where('orderid', $id)->value('couponid');
                $start = DB::table('coupon')->where('coupon_id', $cop_id)->value('start_time');
                $end = DB::table('coupon')->where('coupon_id', $cop_id)->value('end_time');
                if ($start < date('Y-m-d 59:59:59') && $end > date('Y-m-d 00:00:00'))
                {
                    return view('paybill',['user'=>$this->user,'nav'=>$this->nav,'param'=>$param]);
                }else{
                    $param['paybill']->orders_amount = $param['paybill']->orders_amount + $param['paybill']->orders_discount;
                    DB::table('orders')
                        ->where('id', $param['paybill']->id)
                        ->update(['orders_amount' => $param['paybill']->orders_amount]);
                }
            }
        return view('paybill',['user'=>$this->user,'nav'=>$this->nav,'param'=>$param]);
    }


    public function pagepay()
    {
        $result = array();
        $id = Input::all()['id'];
        $result = Order::where('id',$id)
            ->where('orders_user_id',session('user')->id)
            ->where('orders_status',0)
            ->first();
        return view('pay.pagepay.pagepay',compact('result',$result));
    }
    /**
     * 支付成功+生产账单
     * @id付款前，订单清算，后台返回到前台的，订单id
     * @status用户支付返回状态码[1成功付款状态]
     */
    //支付宝支付成功
    public function dobill()
    {
        $out_trade_no = $_GET['out_trade_no'];
        if (!empty($out_trade_no)){
            if (substr($out_trade_no,0,2) =="CZ"){
                $user_id = session('user')->id;
                $log = new Log();
                $log->userid = $user_id;
                $log->action = '充值操作成功';
                $log->detail = '充值用户ID'.$user_id;
                $log->status = 1;
                $log->save();
                $arr = [
                    "isdel" =>1
                ];
                $amount = DB::table('account')->where('out_orderid',$out_trade_no)->first();
                $arr1=[
                    "account"=>$amount->amount
                ];
                $update = DB::table('account')->where('out_orderid',$out_trade_no)->update($arr);
                $update_account = DB::table('frontusers')->where('id',$user_id)->update($arr1);
                if ($update ==false){
                    return back()->withErrors('支付成功!');
                }
             return redirect('/user/account');
            }else{
                $a = Order::where('orders_orderNo',$out_trade_no)->first();
                $user_id = $a->orders_user_id;
                $log = new Log();
                $log->userid = $user_id;
                $log->action = '/dobill';
                $log->detail = '订单付款完成订单ID'.$a->id;
                $log->status = 1;
                $log->save();
            }
        }else{
            return back();
        }
        $id = $a->id;
        $rows = array();
        $rows['orders_status'] =1;
        $rowss['details_status'] =1;
        $res = DB::table('orders')->where('id', $id)->update($rows);
        $ress = DB::table('order_details')->where('details_order_id', $id)->update($rowss);
        $result = Order::where('id',$id)->first();
        $status = $result->orders_status;
        if($status==1){
            $bill = $this->bill->bill_order($id);

            if($bill != 'ok'){
                $result = ['res'=>'error','msg'=>$bill];
            }else{
                $result = ['res'=>'ok','msg'=>'付款成功，已经为您生成近期账单!你可以前往用户中心查看!'];
            }
        }else{
            $result = ['res'=>'error','msg'=>'付款失败!请至用户中心,我的订单重新付款!'];
        }
       return redirect('/user/order');
    }
    //微信支付成功
    public function wxnotify()
    {
    include_once env('WXPAY_PUBLIC').'wxpay/lib/WxPay.Api.php';
    include_once env('WXPAY_PUBLIC').'wxpay/example/log.php';
    $order_num = Input::all()['out_trade_no'];
    ini_set('date.timezone','Asia/Shanghai');
    error_reporting(E_ERROR);
   //初始化日志
    $logHandler= new \CLogFileHandler("./logs/".date('Y-m-d').'.log');
    $log = \Log::Init($logHandler, 15);

    if(isset($_REQUEST["transaction_id"]) && $_REQUEST["transaction_id"] != ""){
        $transaction_id = $_REQUEST["transaction_id"];
        $input = new WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        echo json_encode(WxPayApi::orderQuery($input));
        exit();
    }

    if(isset($order_num) && $order_num != ""){
        $out_trade_no = $order_num;
        $input = new \WxPayOrderQuery();
        $input->SetOut_trade_no($out_trade_no);
        $result_code =  \WxPayApi::orderQuery($input)['trade_state'];
        if ($result_code == 'SUCCESS'){
            if (!empty($out_trade_no)){
                if (substr($out_trade_no,0,2) =="CZ"){
                    $user_id = session('user')->id;
                    $log = new Log();
                    $log->userid = $user_id;
                    $log->action = '充值操作成功';
                    $log->detail = '充值用户ID'.$user_id;
                    $log->status = 1;
                    $log->save();
                    $arr = [
                        "isdel" =>1
                    ];
                    $amount = DB::table('account')->where('out_orderid',$out_trade_no)->first();
                    $arr1=[
                        "account"=>$amount->amount
                    ];
                $update = DB::table('account')->where('out_orderid',$out_trade_no)->update($arr);
                $update_account = DB::table('frontusers')->where('id',$user_id)->update($arr1);
                if ($update ==false){
                    return back()->withErrors('支付成功!');
                }
                }else{
                    $a = Order::where('orders_orderNo',$out_trade_no)->first();
                    $user_id = $a->orders_user_id;
                    $log = new Log();
                    $log->userid = $user_id;
                    $log->action = '/wxnotify';
                    $log->detail = '订单付款完成订单ID'.$a->id;
                    $log->status = 1;
                    $log->save();
                }
            }else{
               $user_id = session('user')->id;
                    $log = new Log();
                    $log->userid = $user_id;
                    $log->action = '充值操作失败';
                    $log->detail = '充值用户ID'.$user_id;
                    $log->status = 0;
                    $log->save();
            }
            $id = $a->id;
            $rows = array();
            $rows['orders_status'] =1;
            $rowss['details_status'] =1;
            $res = DB::table('orders')->where('id', $id)->update($rows);
            $ress = DB::table('order_details')->where('details_order_id', $id)->update($rowss);
            $result = Order::where('id',$id)->first();
            $status = $result->orders_status;
            if($status==1){
                $bill = $this->bill->bill_order($id);

                if($bill != 'ok'){
                    $result = ['res'=>'error','msg'=>$bill];
                }else{
                    $result = ['res'=>'ok','msg'=>'付款成功，已经为您生成近期账单!你可以前往用户中心查看!'];
                }
            }else{
                $result = ['res'=>'error','msg'=>'付款失败!请至用户中心,我的订单重新付款!'];
            }
            return "成功";
        }else{
            return "未支付";
        }
       }
    }
    //支付方式
    public function payType()
    {
        switch ($_POST['paytype']) {
            /*微信扫码支付*/
            case '1':
                include_once env('WXPAY_PUBLIC')."wxpay/lib/WxPay.Api.php";
                include_once env('WXPAY_PUBLIC')."wxpay/example/WxPay.NativePay.php";
                include_once env('WXPAY_PUBLIC').'wxpay/example/log.php';
                $param['orders_amount'] = intval(Input::all()['orders_amount']);
                $param['orders_orderNo'] = Input::all()['orders_orderNo'];
                $param['id'] = Input::all()['id'];
                $this->user = DB::table('frontusers')->find(session('user')->id);
                $param['cart'] = CommonController::shopcart(session('user')->id);
                $param['name'] = $this->user->name;
                return view('wxpay.WXpay',['user' => $this->user, 'param' => $param, 'nav' => $this->nav]);
                break;
            /*支付宝扫码支付* */
            case '2':
                $param = array();
                $param['orders_amount'] = Input::all()['orders_amount'];
                $param['orders_orderNo'] = Input::all()['orders_orderNo'];
                $param['id'] = Input::all()['id'];
                $this->user = DB::table('frontusers')->find(session('user')->id);
                $param['cart'] = CommonController::shopcart(session('user')->id);
                return view('pay.pay', ['user' => $this->user, 'param' => $param, 'nav' => $this->nav]);
                break;
            /*银联支付*/
            case '3':
                break;
            /*余额支付*/
            case '4':
                break;
        }
    }
}
